//
//  KLSettingViewController.m
//  blanket
//
//  Created by Mac on 2017/12/4.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "BLSettingViewController.h"
#import "STPhotoUrlImageBrowerController.h"
#import "BLChangePwdViewController.h"
#import "BLSuggestViewController.h"
#import "BLLoginHomeViewController.h"
#import "BLAboutUsViewController.h"
//#import "STCrashAnimation.h"
#import "UIImage+STTools.h"
#import "BLAnimationControllerViewController.h"
#import "UIViewController+st_starWarAnimation.h"
@interface BLSettingViewController ()<STPhotoUrlImageBrowerControllerDelegate,STActionSheetDelegate,UIViewControllerTransitioningDelegate,UINavigationControllerDelegate>
@property(nonatomic, strong) NSArray  <STTableEasyModel*>                   *dataSouce;
@property(nonatomic, strong) STButton                     *iconButton;
@property(nonatomic, strong) UISwitch                     *messageSwitch;
@property(nonatomic, strong) STPhotoUrlImageBrowerController                     *pickerVC;
@property(nonatomic, strong) STUrlPhotoModel                     *imageModel;

@property(nonatomic, strong) UIViewController                     *animationController;/**< <##> */
@end

@implementation BLSettingViewController

- (void)dealloc{
    
}
#pragma mark --vc 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"个人中心";
    [self configSubView];
    [self reloadData];
    
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (!self.userModel) {
        [self sendMyInfoRequest];
    }
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
#pragma mark --subView
- (void)configSubView{
    __weak typeof(self) weakSelf =  self;
    self.iconButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)
                                                     title:nil
                                                titleColor:nil
                                                 titleFont:0
                                              cornerRadius:20
                                           backgroundColor:nil
                                           backgroundImage:[UIImage imageNamed:@"个人头像"]
                                                     image:nil];
    [self.iconButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedIconCell];
    }];
    self.messageSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
    self.messageSwitch.onTintColor = BL_BlueBackGroundColor;
    

    [self configTableFooter];
}
- (void)configTableFooter{
    __weak typeof(self) weakSelf =  self;
    UIView * footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 100)];
    footer.backgroundColor = self.tableView.backgroundColor;
    STButton * confimButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth , 44)
                                                        title:@"退出登录"
                                                   titleColor:BL_firstTextColor
                                                    titleFont:18
                                                 cornerRadius:0
                                              backgroundColor:[UIColor whiteColor]
                                              backgroundImage:nil
                                                        image:nil];
    [confimButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedLogoutButton];
    }];
    confimButton.st_centerY = 50;
    [confimButton st_showTopLine];
    [confimButton st_showBottomLine];
    confimButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [footer addSubview:confimButton];
    self.tableView.tableFooterView = footer;
}
- (void)reloadData{
    
    NSString *version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    STTableEasyModel * versionModel = [[STTableEasyModel alloc] initWithTextString:@"当前版本"
                                                                      detailString:[NSString stringWithFormat:@"v%@",version]];
    versionModel.accessoryType = UITableViewCellAccessoryNone;
    [self.iconButton sd_setBackgroundImageWithURL:[NSURL URLWithString:self.userModel.face] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"个人头像"]];
    NSString * nickName = self.userModel.username;
    NSArray * sectionOne = @[
                             [[STTableEasyModel alloc] initWithTextString:@"头像" accessoryView:self.iconButton],
                             [[STTableEasyModel alloc] initWithTextString:@"昵称" detailString:nickName],
                             [[STTableEasyModel alloc] initWithTextString:@"修改密码" detailString:@""],
                             [[STTableEasyModel alloc] initWithTextString:@"意见反馈" detailString:@""],
                             //versionModel,
                             [[STTableEasyModel alloc] initWithTextString:@"关于我们" detailString:@""]];
    
    
    self.dataSouce = sectionOne;
    [self.tableView reloadData];
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 24;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuseIdentifier];
        
    }
    cell.textLabel.textColor = UIColorFromRGBA(0x333333);
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
    cell.detailTextLabel.textColor = UIColorFromRGBA(0x999999);
    
    STTableEasyModel * model = self.dataSouce[indexPath.row];
    cell.textLabel.text = model.textString;
    cell.detailTextLabel.text = model.detailString;
    if (model.accessoryView) {
        cell.accessoryView = model.accessoryView;
    }else{
        cell.accessoryType = model.accessoryType;
    }
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    STTableEasyModel * model = self.dataSouce[indexPath.row];
    if (indexPath.row == 0) {
        [self onSelectedIconCell];
    }
    if (indexPath.row == 1) {
        [self onSelectedNickNameCellWithIndexPath:indexPath model:model];
    }
    if (indexPath.row == 2) {
        [self.navigationController pushViewController:[BLChangePwdViewController new] animated:YES];
    }
    if (indexPath.row == 3) {
        [self.navigationController pushViewController:[BLSuggestViewController new] animated:YES];
    }
    if (indexPath.row == 4) {
        //关于我们
        [self.navigationController pushViewController:[BLAboutUsViewController new] animated:YES];
    }
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}
- (void)onSelectedIconCell{
    STUrlPhotoModel * model = [STUrlPhotoModel new];
    model.thumbImage = self.iconButton.currentBackgroundImage;
    if (self.userModel) {
        model.thumbImageUrl = self.userModel.face;
    }
    self.imageModel = model;
    self.pickerVC = [[STPhotoUrlImageBrowerController alloc] initWithArray:@[model] curentIndex:0];
    self.pickerVC.STPhotoUrlImageBrowerControllerdelegate = self;
    self.pickerVC.themeColor = BL_BlueBackGroundColor;
    [self presentViewController:self.pickerVC animated:NO completion:nil];
}
- (void)onSelectedNickNameCellWithIndexPath:(NSIndexPath*)indexPath model:(STTableEasyModel*)model{
    NSString * placeHolder = [NSString stringWithFormat:@"请输入%@",model.textString];
    STTableViewDetailController * detail =
    [[STTableViewDetailController alloc] initWithPlaceholder:placeHolder
                                                       title:model.textString
                                                        text:model.detailString
                                                      handle:^(NSString *text) {
                                                          if (text.length && ![text isEqualToString:model.detailString]) {
                                                              [self sendChangeNickNameRequest:text withModel:model];
                                                          }
                                                          if (!text.length) {
                                                              [SVProgressHUD showErrorWithStatus:@"姓名不能为空"];
                                                          }
                                                          [self.navigationController popViewControllerAnimated:YES];
                                                      }];
    detail.detailLabel.text = @"";
    detail.isShowTextNum = NO;
    [self.navigationController pushViewController:detail animated:YES];
}
#pragma mark --STPhotoUrlImageBrowerControllerDelegate
- (UIView*)STPhotoSystemBrowserControllerDidScrollToIndexpath:(NSIndexPath*)indexPath model:(STUrlPhotoModel*)model{
    return self.iconButton;
}
- (void)rightBarActionFromController:(STPhotoUrlImageBrowerController*)controller currentIndexPath:(NSIndexPath *)curentIndexpath{

    STActionSheet * actionSheet = [[STActionSheet alloc] initWithTitle:nil
                                                          buttonTitles:@[@"拍照",@"从手机相册选择",@"保存图片"] cancelTitle:@"取消"
                                                              delegate:self
                                   ];
    [actionSheet show];
}
#pragma mark --STActionSheetDelegate
- (void)actionSheet:(STActionSheet *)actionSheet didClickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        [self.pickerVC showTakePhotoImagePicker:^(UIImage *image) {
            [self sendIconChangeRequest:image];
        }];
    }
    if (buttonIndex == 1) {
        [self.pickerVC showchosePhotoImagePicker:^(UIImage *image) {
            [self sendIconChangeRequest:image];
        }];
    }
    if (buttonIndex == 2) {
        [PHPhotoLibrary saveImageToAssetsLibrary:self.iconButton.currentBackgroundImage
                                     libraryName:@"铺盖" successHandle:^{
                                         [SVProgressHUD showSuccessWithStatus:@"保存到相册成功"];
                                     } errorHandle:^(STSaveImageError error) {
                                         
                                     }];
    }
}
#pragma mark --Action Method
- (void)onSelectedLogoutButton{
    [self showAlertCancelAndConfirm:@"确定要退出登录吗?" andWithBlock:^(NSString *name) {
        if ([name isEqualToString:@"确认"]) {
            [[STUserManger defult] removeUserPreferce];
            BLLoginHomeViewController * login = [BLLoginHomeViewController new];
            STNavigationController * nav = [[TMNavgationViewController alloc] initWithRootViewController:login];
            [self st_rootViewControllerChangeAnimationToViewController:nav completion:^{
                
            }];

        }
    }];

}
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed{
    NSLog(@"daili");
    return StarWarsGLAnimator.new;
}
- (nullable id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
                                            animationControllerForOperation:(UINavigationControllerOperation)operation
                                                         fromViewController:(UIViewController *)fromVC
                                                           toViewController:(UIViewController *)toVC{
    if (operation == UINavigationControllerOperationPop) {
        return StarWarsGLAnimator.new;
    }
    return nil;
}
#pragma mark --NetWork Method
- (void)sendChangeNickNameRequest:(NSString*)nickName withModel:(STTableEasyModel*)model{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    [dic setObject:debugToken forKey:@"token"];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"index.php/Api/Basics/editUsernameAction"];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if (nickName.length) {
        [dic setObject:nickName forKey:@"username"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 model.detailString = nickName;
                                                 [self.tableView reloadData];
                                                 //NSLog(@"json = %@",dataDic.mj_JSONString);
                                                 [SVProgressHUD showSuccessWithStatus:@"修改成功"];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendIconChangeRequest:(UIImage*)image{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    [dic setObject:debugToken forKey:@"token"];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"index.php/Api/Basics/item_upload"];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    NSData * data =  UIImageJPEGRepresentation(image, 0.5);
    NSString *dataStr = [data base64EncodedStringWithOptions:0];
    [dic setObject:dataStr forKey:@"img"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 NSString * dataStr =  responseObject[@"data"];
                                                 [self sendIconUrlChangedRequestWithFace:dataStr image:image];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendIconUrlChangedRequestWithFace:(NSString*)face image:(UIImage*)image{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    [dic setObject:debugToken forKey:@"token"];
    
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"index.php/Api/Basics/editFaceAction"];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if (face.length) {
        [dic setObject:face forKey:@"face"];
    }
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 //NSString * dataStr =  responseObject[@"data"];
                                                 [self.iconButton setBackgroundImage:image forState:UIControlStateNormal];
                                                 self.imageModel.originImage = image;
                                                 [self.pickerVC reloadData];
                                                 [SVProgressHUD showSuccessWithStatus:@"修改头像成功"];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}

- (void)sendMyInfoRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    [dic setObject:debugToken forKey:@"token"];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"index.php/Api/Basics/MemberListAction"];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 self.userModel = [BLUserModel mj_objectWithKeyValues:responseObject[@"data"]];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
@end
